import 'dart:convert';


import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../Login/LoginVIewController.dart';
import '../Main/Information/InformationView.dart';

final dio = Dio(
  BaseOptions(
    connectTimeout: Duration(seconds: 50),
    receiveTimeout:Duration(seconds: 50),
  ),
);
class ApiManager {
  static Dio _dio = Dio();
  static Future<void> _handleRequest(
      BuildContext context,
      String url,
      Map<String, dynamic> data,
      Function(Map<String, dynamic> responseData) onSuccess,
      ) async {
    String? token = await TokenManager.getToken();
    LoadingDialog.show(context);
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        // 在请求之前添加请求头
        options.headers["satoken"] = token;
        options.headers["loginType"] = "shipper";
        return handler.next(options);
      },
    ));
    // _dio.options.headers["satoken"] = token;

    try {
      Response response = await _dio.post(
        MyServiceUrl.header + url,
        data: data,
        options: Options(
          sendTimeout: Duration(seconds: 2),
          receiveTimeout: Duration(seconds: 50),
        ),
        onSendProgress: (a, b) => print('send ${a / b}'),
        onReceiveProgress: (a, b) => print('received ${a / b}'),
      );
      Map<String, dynamic> jsonMap = json.decode(response.toString());
      // 处理返回的数据
      handleResponse(context, jsonMap, onSuccess);
    } catch (error) {
      print(error);
      // LoadingDialog.hide(context);

      if(error.toString().contains("timeout")) {
        BrnToast.show("网络请求超时", context);
      }else  if(error.toString().contains("Connection failed")){
        BrnToast.show("服务器请求失败", context);
      }else  if(error.toString().contains("connection error")){
        BrnToast.show("服务器请求错误", context);
      }else{
        BrnToast.show(error.toString(), context);
      }

    }
  }

  static Future<void> postData(
      BuildContext context,
      String url,
      Map<String, dynamic> data,
      Function(Map<String, dynamic> responseData) onSuccess,
      ) async {
    _handleRequest(context, url, data, onSuccess);
  }

  static void handleResponse(BuildContext context, Map<String, dynamic> responseData, Function(Map<String, dynamic> responseData) onSuccess) {
    String code = responseData['code'].toString();
    LoadingDialog.hide(context);
    print(responseData);
    if (code == "200") {
      onSuccess(responseData);
    }else if(code == "50010001"||code == "50010002"||code == "50010007"||code == "50010008"||code == "50010009"){
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return BrnDialog(
            titleText: responseData['msg'],
            actionsWidget: [
              TextButton(
                onPressed: () {
                  TokenManager.clearToken();
                  Navigator.of(context).pushAndRemoveUntil(
                      MaterialPageRoute(builder: (builder) {
                        return LoginVC();
                      }), (route) => route == null);
                },
                child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              ),
            ],
          );
        },
      );
    }else if(code == "500100031"){
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return BrnDialog(

            titleText: "未实名认证",
            messageText:"请先完成实名认证",
            actionsWidget: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  Navigator.push( context, FadeRoute(page:InformationView(dataMap: {})));
                },
                child: Text("前往认证",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              ),
            ],
          );
        },
      );
    } else {
      BrnToast.show(responseData['msg'], context);
    }
  }
}